﻿using ImageManager.Common;
using ImageManager.DBAccess;
using ImageManager.Model;
using ImageManager.MyExcep;
namespace ImageManager.ImageService
{
    public abstract class BaseServiceProvider<T> where T : BaseModel, new()
    {
        protected DbQuery<T> qryInstance;
        protected DbUpdater<T> udpInstance;
        protected DbInstance instance;
        protected List<IDefValSetter<T>> defValSetters;
        public BaseServiceProvider()
        {
            instance = ServiceLoader.GetService<DbInstance>();
            qryInstance = new DbQuery<T>(instance);
            udpInstance = CreateUpdateInstance();
            defValSetters = new List<IDefValSetter<T>>();
        }
        public virtual DbUpdater<T> CreateUpdateInstance()
        {
            return new DbUpdater<T>(instance);
        }
        public virtual void AddDefValSetter(IDefValSetter<T> setter)
        {
            defValSetters.Add(setter);
        }

        public virtual T Get(string pk)
        {
            var r = qryInstance.Get(pk);
            if (r == null)
                throw new MyDataNotFoundException();
            return r;
        }
        public virtual void Save(T data)
        {
            foreach (var setter in defValSetters)
            {
                setter.SetupModel(data);
            }
            udpInstance.Save(data);
        }
        public virtual List<T> List(CondCollection cond, int index, int pageSize, out int total)
        {
            return qryInstance.Where(cond).ToPageList(pageSize, index, out total);
        }
        public virtual List<T> List(CondCollection cond, int index, int pageSize, out int total, params OrderByField[] orderBy)
        {
            return qryInstance.Where(cond).OrderBy(orderBy).ToPageList(pageSize, index, out total);
        }
        public virtual List<T> List(CondCollection cond)
        {
            return qryInstance.Where(cond).ToList();
        }
        public virtual void Delete(String pk)
        {
            udpInstance.Delete(pk);
        }
    }
}
